package com.cl.blog.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.common.Const;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BMenu;
import com.cl.blog.entity.BMenuRole;
import com.cl.blog.entity.BRole;
import com.cl.blog.service.BAdminService;
import com.cl.blog.service.BMenuRoleService;
import com.cl.blog.service.BMenuService;
import com.cl.blog.mapper.BMenuMapper;
import com.cl.blog.service.BRoleService;
import com.cl.blog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author object
 * @description 针对表【b_menu】的数据库操作Service实现
 * @createDate 2024-03-16 15:54:45
 */
@Service
public class BMenuServiceImpl extends ServiceImpl<BMenuMapper, BMenu>
		implements BMenuService {

	@Resource
	BMenuRoleService bMenuRoleService;
	@Resource
	JwtUtil jwtUtil;
	@Resource
	BAdminService bAdminService;
	@Resource
	BRoleService bRoleService;


	@Override
	public List<BMenu> listMenu(String token) {
		// 获取登录者的id
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);

		BAdmin bAdmin = bAdminService.getById(claim.getSubject());

		List<BMenu> pMenu = new ArrayList<>();

		// 查看登录者角色等级
		BRole bRole = bRoleService.getById(bAdmin.getRoleId());

		System.out.println("角色等级==========" + bRole.getId());

		if (bRole.getRole() == 1) {
			// 是超级管理员，直接获取所有列表
			// 获取父级数据
			pMenu = this.list(new QueryWrapper<BMenu>()
					.isNull("pid")
			);

			for (BMenu bMenu : pMenu) {
				List<BMenu> cMenu = this.list(new QueryWrapper<BMenu>()
						.eq("pid", bMenu.getId())
				);
				bMenu.setChildMenu(cMenu);
			}
		} else {
			List<Integer> menuIds = bMenuRoleService.getMenuIds(bRole.getId());
			System.out.println("获取的所有id---" + menuIds);

			pMenu = this.list(new QueryWrapper<BMenu>().in("id", menuIds).isNull("pid"));

			for (BMenu bMenu : pMenu) {
				List<BMenu> cMenu = this.list(new QueryWrapper<BMenu>()
						.eq("pid", bMenu.getId())
						.in("id", menuIds)
				);
				bMenu.setChildMenu(cMenu);
			}

		}

		System.out.println("最终的数据---" + pMenu);
		return pMenu;
	}
}




